//
//  QJMineInforVC.m
//  QuanJieShopProject
//
//  Created by apple on 2018/2/7.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "QJMineInforVC.h"
#import "QJMinePasswordVC.h"
#import "YFUserStatusAndTypeTool.h"
#import "YFAppVersionUpdate.h"

@interface QJMineInforVC () <UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSInteger _userState;
    NSInteger _user_type;  // 1 是 泉界会员，2 是泉界创客，3，是泉界商家
}
@property (nonatomic, strong) NSString *userNickname;
@property (nonatomic, strong) NSString *sexStr;//0保密1男2女
@property (nonatomic, strong) NSData *imageData;
@property (nonatomic, strong) UIImage *headerImage;
@end

@implementation QJMineInforVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"个人信息";
    self.userBtn.layer.cornerRadius = 15;
    self.userBtn.layer.masksToBounds = YES;
    self.view.backgroundColor = HexRGB(0xe6e6e6);
    
     NSString *token = [QJUserInfo getToken];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    NSString *str = [NSString stringWithFormat:@"%@/%@&&token=%@",kApiPrefix,kModifyProfile,token];
    [session GET:str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"下载的进度");
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        NSLog(@"请求成功:%@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败:%@", error);
    }];
    
    [WWNetRequest fetchModifyProfileWithParameters:nil success:^(id response) {
        NSLog(@"修改个人信息 response = %@", response);
        
        if (response) {
            UserInfoModel *model = [QJUserInfo getCurrentUser];
            model.user_nickname = self.userNickname;
            model.sex = self.sexStr;
            [self updateUserInformationAction];
        }
    } failure:^(NSDictionary *error) {
        NSLog(@"修改个人信息 error = %@", error);
    }];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self setupVersion];
    
    [self setNavAlpha:YES];
    //控件不被导航栏遮挡
    self.navigationController.navigationBar.translucent = NO;
    [self updateUserInformationAction];
    
    // 用户类型, 用新接口判断
    [YFUserStatusAndTypeTool fetchUserStatus:^(NSInteger status, NSInteger userType) {
        _userState = status;
        _user_type = userType;
        
        NSString *typeStr;
        if (_userState == -1) {  // 未找到店铺   新用户注册就是这个
            typeStr = @"泉界会员";
        }else if (_userState == 1) {  // 审核通过
            typeStr = @"泉界商家";
        }else if (_userState == 2 || _userState == 0) {  // 0未审核  2审核未通过
            if (_user_type == 1) {
                typeStr = @"泉界会员";
            }else if (_user_type == 2){
                typeStr = @"泉界创客";
            }else if (_user_type == 3){ // 不可能有这种情况
                typeStr = @"泉界商家";
            }
        }
    }];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self setNavAlpha:NO];
    self.navigationController.navigationBar.translucent = YES;

}
- (void)updateUserInformationAction{
    self.userHeaderImage.layer.cornerRadius = 20.0;
    self.userHeaderImage.layer.masksToBounds = YES;
    [self.userHeaderImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",NET_BASEURL,[QJUserInfo headerImageUrl]]] placeholderImage:[UIImage imageNamed:@"noHeaderImage"]];
    self.userNicknameLabel.text = [NSString stringWithoutNilFormart:[QJUserInfo nickname]];
    self.userNameLabel.text = [NSString stringWithoutNilFormart:[QJUserInfo userName]];
    //user_type =1  是 泉界会员，2 是泉界创客，3，是泉界商家
    NSString *userType = [QJUserInfo getUserType];
    NSString *typeStr;
    if ([userType isEqualToString:@"1"]) {
        typeStr = @"泉界会员";
    }else if ([userType isEqualToString:@"2"]){
        typeStr = @"泉界创客";
    }else if ([userType isEqualToString:@"3"]){
        typeStr = @"泉界商家";
    }
    self.userVipLabel.text = typeStr;
    NSString *sexStr = [QJUserInfo getUserSex];
    if ([sexStr isEqualToString:@"2"]) {
        sexStr = @"女";
    }else if ([sexStr isEqualToString:@"1"]){
        sexStr = @"男";
    }else{
        sexStr = @"保密";
    }
    self.userSexLabel.text = sexStr;
    self.userNickname = [NSString stringWithoutNilFormart:[QJUserInfo nickname]];
    self.sexStr = sexStr;
}
- (IBAction)headetImageBtnClickAction:(UIButton *)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"设置头像" message:@"请选择头像来源" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self gotoIamgePickerWith: UIImagePickerControllerSourceTypeCamera];
    }];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self gotoIamgePickerWith: UIImagePickerControllerSourceTypePhotoLibrary];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cameraAction];
    [alert addAction:photoAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
- (IBAction)userNicknameBtnClickAction:(UIButton *)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"编辑昵称" preferredStyle:UIAlertControllerStyleAlert];
    
    //在AlertView中添加一个输入框
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入昵称";
    }];
    
    //添加一个确定按钮 并获取AlertView中的第一个输入框 将其文本赋值给BUTTON的title
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *envirnmentNameTextField = alertController.textFields.firstObject;
        self.userNickname = envirnmentNameTextField.text;
        [self changeUserInfoAction];
    }]];
    //添加一个取消按钮
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    //present出AlertView
    [self presentViewController:alertController animated:true completion:nil];
}
- (IBAction)userSexBtnClickAction:(UIButton *)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"编辑性别" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *bmAction = [UIAlertAction actionWithTitle:@"保密" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.sexStr = @"0";
        [self changeUserInfoAction];
    }];
    UIAlertAction *nanAction = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.sexStr = @"1";
        [self changeUserInfoAction];
    }];
    UIAlertAction *nvAction = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.sexStr = @"2";
        [self changeUserInfoAction];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:bmAction];
    [alert addAction:nanAction];
    [alert addAction:nvAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
- (IBAction)userSecretBtnClickAction:(UIButton *)sender {
    QJMinePasswordVC *VC = [[QJMinePasswordVC alloc]init];
    KPushViewControllerAction(VC);
}
- (IBAction)userLogoutBtnClickAction:(UIButton *)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您确定要退出当前用户吗?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
        [WWNetRequest fetchLogoutWithParameters:kLogout success:^(id response) {
            NSLog(@"退出 response = %@", response);

            if (response) {
                //清除当前的用户信息
                [QJUserInfo RemoveCurrentUser];
                [MBPHUD showAlertWithTitle:@"您已退出当前账户"];
                KPopViewControllerAction;
            }
        } failure:^(NSDictionary *error) {
            NSLog(@"退出 error = %@", error);
        }];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:okAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark -- 修改个人信息
- (void)changeUserInfoAction{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.userNickname forKey:@"nickname"];
    [dict setObject:self.sexStr forKey:@"sex"];
    
    NSLog(@"修改个人信息 dict=%@", dict);
    
    [WWNetRequest fetchModifyProfileWithParameters:dict success:^(id response) {
        NSLog(@"修改个人信息 response = %@", response);

        if (response) {
            UserInfoModel *model = [QJUserInfo getCurrentUser];
            model.user_nickname = self.userNickname;
            model.sex = self.sexStr;
            [self updateUserInformationAction];
        }
    } failure:^(NSDictionary *error) {
        NSLog(@"修改个人信息 error = %@", error);
    }];
}




#pragma mark -- 头像上传
- (void)uploadHeaderImageAction{
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"head_pic" forKey:@"savepath"];
    [dict setObject:@"banner" forKey:@"pictitle"];
    [dict setObject:@"image" forKey:@"dir"];
    

    [[HttpManager shareHttpManager] postImagefileWithUrl:kUploadImage parameter:dict withImageFile:self.headerImage hiddenHUD:YES HUDTitle:@"正在上传头像" success:^(NSURLSessionDataTask *operetion, id response) {
        NSLog(@"正面 = response = %@", response);
        if (response) {
            UserInfoModel *model = [QJUserInfo getCurrentUser];
            model.avatar = response[@"url"];
            
            
            [self.userHeaderImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",NET_BASEURL, model.avatar]] placeholderImage:[UIImage imageNamed:@"noHeaderImage"]];
        }
    } failure:^(NSURLSessionDataTask *operetion, id response) {
        [MBPHUD showAlertWithTitle:@"身份证正面照提交失败,请重新提交!"];
    }];

}
#pragma mark -- 选择图片来源
- (void)gotoIamgePickerWith:(NSUInteger)sourceType{
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            [MBPHUD showAlertWithTitle:@"您没有对相机授权!"];
            return;
        }
        
    }else{
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            [MBPHUD showAlertWithTitle:@"您没有对相册授权!"];
            return;
        }
    }
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
    imagePickerController.sourceType = sourceType;
    
    [self presentViewController:imagePickerController animated:YES completion:^{
    }];
}
#pragma mark UIImagePickerControllerDelegate
//该代理方法仅适用于只选取图片时
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {
    
    [self dismissViewControllerAnimated:YES completion:^{
        NSData *data = UIImageJPEGRepresentation(image, 1);
        self.imageData = data;
        self.headerImage = image;

        WEAKSELF
        [weakSelf uploadHeaderImageAction];
    }];
}

#pragma mark - 版本显示
- (void)setupVersion {

    CGFloat btnW = 300;
    CGFloat btnH = 50;
    CGFloat btnX = (UISCREEN_WIDTH - btnW)/2;
    CGFloat btnY = (UISCREEN_HEIGHT - btnH - Height_NavContentBar) - 20; // 20 是底部间距
//    NSLog(@"btnY = %f", btnY);
//    NSLog(@"height = %f", self.view.frame.size.height);
//    NSLog(@"UISCREEN_HEIGHT = %f", UISCREEN_HEIGHT);
    NSString *version = [YFGlobalTool appVersion];
 // 有新版本,请及时更新!
    
    NSString *title = @"";
    // 更新提示
    YFAppVersionUpdate *update = [YFAppVersionUpdate sharedInstance];
    if (update.isUpdate) {
        title = [NSString stringWithFormat:@"版本:%@(有新版本,请及时更新!)", version];
    }else {
        title = [NSString stringWithFormat:@"版本:%@", version];
    }
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(btnX, btnY, btnW, btnH)];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:btn];
    
}


@end
